package com.whzykj.ctrl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DbUtil;
import com.whzykj.common.DictCache;
import com.whzykj.model.RechargeActivityDetails;
import com.whzykj.model.RechargeBill;
import com.whzykj.model.Userinfo;

public class AcctController extends Controller{

	public void index() {
		this.renderJsp("/admin/system/acct/acctlist.jsp");
	}
	
	/****
	 * 客户列表
	 */
	public void custlist() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

		Integer station = this.getParaToInt("station");
		
		String sqlBefore = " SELECT d.*,a.amount,a.acct_id  ";
		StringBuffer sqlAfter = new StringBuffer(" FROM (SELECT c.cust_id,c.CUST_NAME,c.CUST_SEX,c.CUST_IDENTITY,c.MOBILE,s.STATION_ID,s.STATION_NAME FROM customer c,STATION s WHERE c.STATION_ID=s.STATION_ID    ");
		
		if (station != null && station != -1) {
			sqlAfter.append(" AND s.STATION_ID=" + station);
		}
		String custname=this.getPara("custname");
		if(custname!=null && custname.trim().length()!=0){
			sqlAfter.append(" and c.CUST_NAME like '%"+custname+"%'");
		}
		String mobile=this.getPara("mobile");
		if(mobile!=null && mobile.trim().length()!=0){
			sqlAfter.append(" and c.MOBILE like '%"+mobile+"%'");
		}
		
		sqlAfter.append(" ) d LEFT JOIN account a ON d.CUST_ID=a.cust_id  ORDER BY d.cust_id DESC ");
		
		Page<Record> paginate = Db.paginate(page, rows, sqlBefore,sqlAfter.toString());
		List<Record> custlist = paginate.getList();
		if (custlist != null && custlist.size() > 0) {
			for (Record rd  : custlist) {
				BigDecimal amountstr = rd.getBigDecimal("amount");
				
				rd.set("amountstr", CommonUtils.formatCommaAnd2Point(amountstr));
				
				Object acctobj = rd.get("acct_id");
				if(acctobj != null){
					int acct_id = rd.getInt("acct_id");//账户ID
					String sql=" select sum(amount) as pre_amount from RechargeBill where trade_status='00' and acct_id=? order by create_time desc ";
					Record rerd = Db.findFirst(sql, acct_id);
					if(rerd != null)
					{
						rd.set("pre_amount",  CommonUtils.formatCommaAnd2Point(rerd.getBigDecimal("pre_amount")));
					}
				}else{
					rd.set("pre_amount", CommonUtils.formatCommaAnd2Point(""));
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", custlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}
	
	/*******
	 * 后台充值
	 */
	@Before(Tx.class)
	public void rechargeBill() {
		String cust_id = getPara("cust_id");
		String bank_type = getPara("bank_type");
		String bank_name = getPara("bank_name");
		String buyer_login_id = getPara("buyer_login_id");
		String amount = getPara("amount");// 充值金额
		String trade_no = getPara("trade_no");
		String recharge_type = getPara("recharge_type");
		String station_id = getPara("station_id");
		String remarks=getPara("pictureSrc");
		
		Object obj = this.getSessionAttr("LOGIN_USER");
		Userinfo userinfo = (Userinfo) obj;
		int userid = userinfo.getInt("userid");

		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("cust_id", cust_id);
		paraMap.put("bank_type", bank_type);
		paraMap.put("bank_name", bank_name);
		paraMap.put("buyer_login_id", buyer_login_id);
		paraMap.put("amount", amount);
		paraMap.put("trade_no", trade_no);
		paraMap.put("recharge_type", recharge_type);
		paraMap.put("station_id", station_id);
		paraMap.put("userid", userid);
		paraMap.put("remarks", remarks);

		boolean save = RechargeBill.dao.recharge(paraMap);
		this.renderText(save ? "0" : "1");
	}
	
	public void reindex() {
		setAttr("acct_id",this.getPara(0));
		
		this.renderJsp("/admin/system/acct/rechargelist.jsp");
	}
	
    /*****
     * 确认充值列表	
     */
	public void rechargelist() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

		String acct_id = getPara("acct_id");
		
		String sqlBefore = " SELECT c.cust_id,c.CUST_NAME,c.CUST_SEX,c.CUST_IDENTITY,c.MOBILE,a.acct_id,a.amount,b.sn,b.amount AS pre_amount,b.trade_status,b.create_time,d.activity_id,d.activity_amount,d.activity_sn   ";
		StringBuffer sqlAfter = new StringBuffer("  FROM customer c,account a,RechargeBill b,rechargeactivitybill d    ");
		sqlAfter.append(" WHERE c.cust_id=a.cust_id AND b.acct_id=a.acct_id AND b.sn=d.recharge_sn   ");
		
		if (acct_id != null && !"".equals(acct_id)) {
			sqlAfter.append(" and a.acct_id = " + acct_id + " ");
		}

		sqlAfter.append(" ORDER BY b.create_time DESC ");
		
		Page<Record> paginate = Db.paginate(page, rows, sqlBefore,sqlAfter.toString());
		List<Record> custlist = paginate.getList();
		if (custlist != null && custlist.size() > 0) {
			for (Record rd  : custlist) {
				BigDecimal pre_amount = rd.getBigDecimal("pre_amount");
				rd.set("amountstr", CommonUtils.formatCommaAnd2Point(pre_amount));
				
				rd.set("activity_amountstr", CommonUtils.formatCommaAnd2Point(rd.getBigDecimal("activity_amount")));
				
				Object activity_idobj = rd.get("activity_id");
				if(activity_idobj != null){
					int activity_id = rd.getInt("activity_id");//账户ID
					String sql=" select activity_name from Recharge_Activity where id=? ";
					Record rerd = Db.findFirst(sql, activity_id);
					if(rerd != null)
					{
						rd.set("activity_name",  rerd.getStr("activity_name"));
					}
				}else{
					rd.set("activity_name", "");
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", custlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}
	
	
	public void rechargeindex() {
		setAttr("acct_id",this.getPara(0));
		
		this.renderJsp("/admin/system/acct/chargerd.jsp");
	}
	
	/****
	 * 确认充值
	 */
	public void recharge() {
		
		Object obj = this.getSessionAttr("LOGIN_USER");
		Userinfo userinfo = (Userinfo) obj;
		int userid = userinfo.getInt("userid");
		String pwd = this.getPara("pwd");
		String password=HashKit.md5(pwd);
		Object[] params = { userid,password};
		Userinfo user = Userinfo.dao
				.findFirst(
						"select * from Userinfo where (userid=? and password=?) and enable=1 and (role<=2 or role=8 or role=9)",
						params);
		if (user == null) {
			this.renderText("2");
		}else{
			String sn = this.getPara("sn");
			String activity_sn = this.getPara("activity_sn");
			String cust_id = this.getPara("cust_id");
			String acct_id = this.getPara("acct_id");
			String pre_amount = this.getPara("pre_amount");
			String activity_amount = this.getPara("activity_amount");
			
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("sn", sn);
			paraMap.put("activity_sn", activity_sn);
			paraMap.put("cust_id", cust_id);
			paraMap.put("acct_id", acct_id);
			paraMap.put("userid", userid);
			paraMap.put("amount", pre_amount);
			paraMap.put("activity_amount", activity_amount);
			String save = RechargeBill.dao.confirmrecharge(paraMap);
			this.renderText(save);
		} 
	}
	
	/*
	 * 关闭充值
	 */
	public void reclose(){
		String sn=this.getPara("sn");
		String activity_sn=this.getPara("activity_sn");
		List<String> sqlList=new ArrayList<String>();
		StringBuffer sql=null;
		if(sn!=null && sn.trim().length()>0){
			sql=new StringBuffer("update rechargebill set trade_status='03' where sn='"+sn+"'");
			sqlList.add(sql.toString());
		}
		if(activity_sn!=null && activity_sn.trim().length()>0){
			sql=new StringBuffer("update rechargebill set trade_status='03' where sn='"+activity_sn+"'");
			sqlList.add(sql.toString());
		}
		try{
			boolean res=DbUtil.batch(sqlList);
			this.renderText(res?"1":"0");
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/*****
     * 充值记录
     */
	public void rechargerd() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

		String acct_id = getPara("acct_id");
		
		String starttime = this.getPara("start_time");
		String endtime = this.getPara("end_time");
		
		String recharge_types = this.getPara("recharge_type");
		
		String sqlBefore = " SELECT r.create_time,c.CUST_NAME,c.MOBILE,s.STATION_ID,s.STATION_NAME,r.amount,r.recharge_type,r.sn   ";
		StringBuffer sqlAfter = new StringBuffer("  FROM customer c,STATION s,account a,rechargebill r WHERE c.STATION_ID=s.STATION_ID AND a.cust_id=c.cust_id AND r.acct_id = a.acct_id AND r.trade_status='02'    ");
		if (acct_id != null && !"".equals(acct_id)) {
			sqlAfter.append(" and a.acct_id = " + acct_id + " ");
		}
		if (recharge_types != null && !"".equals(recharge_types) && !"-1".equals(recharge_types)) {
			sqlAfter.append(" and r.recharge_type = '" + recharge_types + "' ");
		}
		if (starttime != null && !"".equals(starttime) && endtime != null
				&& !"".equals(endtime)) {
			sqlAfter.append(" and r.create_time >= '" + starttime
					+ " 00:00:00' and r.create_time <= '" + endtime
					+ " 23:59:59' ");
		}
		sqlAfter.append(" ORDER BY r.create_time DESC ");
		
		Page<Record> paginate = Db.paginate(page, rows, sqlBefore,sqlAfter.toString());
		List<Record> custlist = paginate.getList();
		if (custlist != null && custlist.size() > 0) {
			for (Record rd  : custlist) {
				String recharge_type = rd.getStr("recharge_type");
				String recharge_typename = DictCache.cache.getDicByText(String.valueOf(recharge_type), "CHANGE_TYPE");
				rd.set("recharge_typename", recharge_typename);
				
				String sn = rd.getStr("sn");
				String sql = " SELECT b.username FROM rechargeactivitybill a,userinfo b WHERE a.recharge_person=b.userid AND a.recharge_sn='"+sn+"' ";
				Record rds = Db.findFirst(sql);
				if(rds != null)
				{
					rd.set("username", rds.getStr("username"));
				}else{
					rd.set("username", "");
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", custlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}
	
	public void transrdindex() {
		setAttr("acct_id",this.getPara(0));
		
		this.renderJsp("/admin/system/acct/transrd.jsp");
	}
	
	/*****
     * 交易记录
     */
	public void transrd() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

		String acct_id = getPara("acct_id");
		
		String starttime = this.getPara("start_time");
		String endtime = this.getPara("end_time");
		
		String sqlBefore = " SELECT r.create_time,c.CUST_NAME,c.MOBILE,s.STATION_ID,s.STATION_NAME,a.amount,r.change_type,r.seq_flag,r.pre_amount,r.amount fix_amount   ";
		StringBuffer sqlAfter = new StringBuffer("  FROM customer c,STATION s,account a,account_seq r WHERE c.STATION_ID=s.STATION_ID AND a.cust_id=c.cust_id AND r.acct_id = a.acct_id     ");
		if (acct_id != null && !"".equals(acct_id)) {
			sqlAfter.append(" and a.acct_id = " + acct_id + " ");
		}
		
		if (starttime != null && !"".equals(starttime) && endtime != null
				&& !"".equals(endtime)) {
			sqlAfter.append(" and r.create_time >= '" + starttime
					+ " 00:00:00' and r.create_time <= '" + endtime
					+ " 59:59:59' ");
		}
		sqlAfter.append(" ORDER BY r.create_time DESC ");
		
		Page<Record> paginate = Db.paginate(page, rows, sqlBefore,sqlAfter.toString());
		List<Record> custlist = paginate.getList();
		if (custlist != null && custlist.size() > 0) {
			for (Record rd  : custlist) {
				String change_type = rd.getStr("change_type");
				String change_typename = DictCache.cache.getDicByText(String.valueOf(change_type), "CHANGE_TYPE");
				rd.set("change_typename", change_typename);
				
				BigDecimal pre_amount = rd.getBigDecimal("pre_amount");// 变动前总金额
				BigDecimal fix_amount = rd.getBigDecimal("fix_amount");// 变动后总金额
				
				String seq_flag = rd.getStr("seq_flag");
				if ("00".equals(seq_flag)) {
					BigDecimal fix = fix_amount.subtract(pre_amount);
					rd.set("fix_amount", "+￥" + fix);
				} else if ("01".equals(seq_flag)) {
					BigDecimal fix = pre_amount.subtract(fix_amount);
					rd.set("fix_amount", "-￥" + fix);
				}
				
				rd.set("amountstr", "￥" + CommonUtils.formatCommaAnd2Point(fix_amount));
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", custlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}
	
	/**
	 * 根据站点ID和充值金额查找对应的充值活动
	 */
	public void findActivityAmount(){
		int station_id=this.getParaToInt("stationid");
		int amount=this.getParaToInt("amount");
		RechargeActivityDetails rad=RechargeActivityDetails.me.findValidRechargeActivityDetails(station_id,amount);
		int activity_amount=0;
		if(rad!=null){
			activity_amount=rad.getBigDecimal("activity_amount").intValue();
		}
		this.renderText(""+activity_amount);
	}
	
	/**
	 * 根据客户编号查询客户客户账号是否存在（存在则返回"1"，不存在返回"0"）
	 * @param custid
	 */
	public void findAcctExistsByCustid(){
		Integer custid=this.getParaToInt("custid");
		int cnt=Db.queryLong("select COUNT(1) FROM account WHERE cust_id="+custid).intValue();
		this.renderText(""+cnt);
	}
}
